//
//  CustomNotificationServer.m
//  WeCommunity
//
//  Created by mac on 2017/8/11.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "CustomNotificationServer.h"

#import <AVOSCloudLiveQuery/AVOSCloudLiveQuery.h>

#define SYSTEMNOTI_CLASS_NAME @"SystemNotification"

static CustomNotificationServer * customNotificationServer = nil;

@interface CustomNotificationServer ()<AVLiveQueryDelegate>

@property (nonatomic,strong) AVLiveQuery * systemLiveQuery;

@end

@implementation CustomNotificationServer

+(CustomNotificationServer *)shared
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        customNotificationServer = [[CustomNotificationServer alloc] init];
        
    });
    return customNotificationServer;
}

#pragma mark -订阅
-(void)addSystemNotiSubscribe
{
    //添加系统通知的订阅
    [[CustomNotificationServer shared] loadSystemNotificationComplete:^(BOOL success, NSString *error, SystemNotiModel *data) {
        if (success) {
            self.systemModel = data;
            [self screeningData];
        }
    }];
}

-(void)showAlertWithSystemModel:(SystemNotiModel *)data
{
    NSString * cancelTitle = data.canCancel ? @"取消" : @"";
    [UITool systemAlertWithTitle:data.title
                      andMessage:data.message
                   actionTextOne:cancelTitle
                   actionTextTwo:@"确定"
                  actionOneBlock:^{
                      
                  }
                  actionTwoBlock:^{
                      NSURL * url = [NSURL URLWithString:data.linkUrl];
                      UIApplication *application = [UIApplication sharedApplication];
                      if ([application canOpenURL:url])
                      {
                          [application openURL:url];
                      }
                  }];
}

#pragma mark - 订阅系统通知
-(void)loadSystemNotificationComplete:(void(^)(BOOL success, NSString * error, SystemNotiModel * data))complete
{
    AVQuery *query = [AVQuery queryWithClassName:SYSTEMNOTI_CLASS_NAME];

//    [query whereKey:@"available" equalTo:@(true)];//查询条件
    [query orderByDescending:@"createdAt"]; //按时间排序 降序
    query.limit = 20; // 最多返回 x 条结果
    
    //添加订阅
    self.systemLiveQuery = [[AVLiveQuery alloc] initWithQuery:query];
    self.systemLiveQuery.delegate = self;
    [self.systemLiveQuery subscribeWithCallback:^(BOOL succeeded, NSError * _Nonnull error) {
        /* Subscribed. */
        if (succeeded) {
            NSLog(@"订阅系统消息成功！");
        }else{
            NSLog(@"订阅系统消息失败！原因：%@",error.userInfo[@"NSLocalizedDescription"]);
        }
    }];
    
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }else{
            if (objects.count > 0) {
                for (NSDictionary * dic in objects) {
                    self.systemModel = [SystemNotiModel setValueFormObject:dic];
                    if (self.systemModel.available) {
                        break;
                    }
                }
                
                if (self.systemModel.available) {
                    complete(YES,nil,self.systemModel);
                }else{
                    complete(NO,@"没有可用的系统通知！",self.systemModel);
                }
            }else{
                complete(NO,@"暂无系统通知！",nil);
            }
        }
    }];
}

- (void)liveQuery:(AVLiveQuery *)liveQuery objectDidCreate:(id)object {
    if (liveQuery == self.systemLiveQuery) {
        NSLog(@"发现新创建的系统消息：%@",object);
        SystemNotiModel * data = [SystemNotiModel setValueFormObject:object];
        if (data.available) {
            self.systemModel = data;
            [self screeningData];
        }
    }
}

- (void)liveQuery:(AVLiveQuery *)liveQuery objectDidUpdate:(id)object updatedKeys:(NSArray<NSString *> *)updatedKeys {
    if (liveQuery == self.systemLiveQuery) {
        NSLog(@"发现新修改的一条系统消息：%@",object);
        SystemNotiModel * data =  [SystemNotiModel setValueFormObject:object];
        if (data.available) {
            self.systemModel = data;
            [self screeningData];
        }
    }
}

-(void)screeningData
{
    NSString * appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    if (self.systemModel.available) {
        if ([self.systemModel.version doubleValue] > [appVersion doubleValue]) {
            [self showAlertWithSystemModel:self.systemModel];
        }else if(self.systemModel.version.length == 0){
            [self showAlertWithSystemModel:self.systemModel];
        }
    }
}

@end
